package com.sqlcheck.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 简化的AI并行处理配置
 * 提供AI增强验证专用的线程池配置
 * 
 * @author Claude
 * @version v1.0
 * @since 2025-09-11
 */
@Slf4j
@Configuration
public class SimpleAIParallelConfig {
    
    @Value("${ai.verification.parallel.enabled:true}")
    private boolean enabled;
    
    @Value("${ai.verification.parallel.thread-count:6}")
    private int threadCount;
    
    @Value("${ai.verification.parallel.max-thread-count:12}")
    private int maxThreadCount;
    
    @Value("${ai.verification.parallel.queue-capacity:50}")
    private int queueCapacity;
    
    @Value("${ai.verification.parallel.keep-alive-seconds:300}")
    private int keepAliveSeconds;

    /**
     * AI验证专用线程池
     * 仅在启用并行处理时创建
     */
    @Bean("aiVerificationExecutor")
    @ConditionalOnProperty(name = "ai.verification.parallel.enabled", havingValue = "true", matchIfMissing = true)
    public ThreadPoolTaskExecutor aiVerificationExecutor() {
        log.info("创建AI验证线程池 - 核心线程数: {}, 最大线程数: {}, 队列容量: {}", 
                threadCount, maxThreadCount, queueCapacity);
        
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadCount);
        executor.setMaxPoolSize(maxThreadCount);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix("ai-verify-");
        
        // 使用调用者执行策略，防止任务丢失
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 等待任务完成后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        
        executor.initialize();
        
        log.info("AI验证线程池创建完成");
        return executor;
    }
    
    /**
     * 检查是否启用并行处理
     */
    public boolean isParallelEnabled() {
        return enabled;
    }
    
    /**
     * 获取配置的线程数
     */
    public int getThreadCount() {
        return threadCount;
    }
    
    /**
     * 获取最大线程数
     */
    public int getMaxThreadCount() {
        return maxThreadCount;
    }
}